#include <string.h>
#include <jni.h>
#include <stdio.h>
#include <time.h>
#include "PositionOffset.h"
#include "com_jcobra_gpsoffset_XYOffset.h"


JNIEXPORT jdoubleArray JNICALL Java_com_jcobra_gpsoffset_XYOffset_xyOffset
  (JNIEnv *env, jobject thiz, jdouble x, jdouble y)
{
	struct timespec now;
	clock_gettime(CLOCK_REALTIME, &now);

	LOGI("x is %f,y is %f,%d",x,y,now.tv_sec);
    int nInit = 1;
    double longitude;
    double latitude;
    unsigned int fx = 0;
    unsigned int fy = 0;
    double* pXY = (double*) malloc(2*sizeof(double));
    if(NULL == pXY){
    	return NULL;
    }
    memset(pXY,0,2*sizeof(double));

    longitude = x * 3686400.0;
    latitude = y * 3686400.0;
//if(now.tv_sec < 1367337600){//1325347200
							//1367337600
    if (wgtochina_lb(0, (int) longitude, (int) latitude, 0, 0,
           (int) 0, &fx,&fy) != 0x00000000) {
    	pXY[0] = fx/3686400.0;
    	pXY[1] = fy/3686400.0;
       return pXY;
    }
    if (wgtochina_lb(nInit, (int) longitude, (int) latitude, 0, 0,
           (int) 0,  &fx,&fy) != 0x00000000) {
    	pXY[0] = fx/3686400.0;
    	pXY[1] = fy/3686400.0;
    	return pXY;
    }
//}
    pXY[0] = fx/3686400.0;
    pXY[1] = fy/3686400.0;
    LOGI("fx is %f,fy is %f",pXY[0],pXY[1]);
    jdoubleArray doubleArray = (*env)->NewDoubleArray(env, 2);
    (*env)->SetDoubleArrayRegion( env, doubleArray, 0, 2, (const jdouble*) pXY );

    return doubleArray;
}
//
//void test(){
//	double lng,lat;
//	    unsigned int wg_lng, wg_lat,real_lng,real_lat,seconds,china_lng, china_lat,wg_time, err;
//	    int wg_heit, wg_week;
//
//
//	    real_lng=(unsigned int)OldLon;
//	    real_lat=(unsigned int)OldLat;
//
//	    time_t timep;
//	    time(&timep);
//
//	    wg_lng = (unsigned int)(((float)real_lng)*SM_LONLAT_TRANS_CONST);
//	    wg_lat = (unsigned int)(((float)real_lat)*SM_LONLAT_TRANS_CONST);
//	    wg_heit=0;
//	    seconds = (unsigned int)timep - DELTA_SECONDS_FROM_EPO_TO_1980_1_6;
//	    wg_week = seconds / WEEK_SECONDS;
//	    wg_time = (seconds % WEEK_SECONDS) * 1000;
//
//	    static int flag=0;
//	    if(flag==0)
//	    {
//	      wgtochina_lb(0,wg_lng,wg_lat,wg_heit, wg_week, wg_time,&china_lng,&china_lat);
//	      flag=1;
//
//	    }
//
//	    wgtochina_lb(1,wg_lng,wg_lat,wg_heit, wg_week, wg_time,&china_lng,&china_lat);
//	    china_lng = (int)(((float)china_lng)/SM_LONLAT_TRANS_CONST);
//	    china_lat = (int)(((float)china_lat)/SM_LONLAT_TRANS_CONST);
//	    *newLon=china_lng;
//	    *newLat=china_lat;
//}
